<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="构建状态" prop="buildstate">
        <el-select v-model="queryParams.buildstate" placeholder="请选择" @change="handleQuery">
          <el-option label="未构建" value="0"></el-option>
          <el-option label="构建中" value="1"></el-option>
          <el-option label="已取消" value="2"></el-option>
          <el-option label="构建成功" value="3"></el-option>
          <el-option label="构建失败" value="-1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['resource:project:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange"
              border highlight-current-row align="center">
<!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="主键ID" align="center" prop="id"/>
      <el-table-column label="项目名称" align="center" prop="name"/>
      <el-table-column label="git地址" align="center" prop="url"/>
      <el-table-column label="分支名称" align="center" prop="branches"/>
      <el-table-column label="上次构建时间" align="center" prop="lastbuild" width="180">
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.lastbuild, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="描述信息" align="center" prop="description"/>
      <el-table-column label="构建状态" align="center" prop="buildstate">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.buildstate===0">未构建</el-tag>
          <el-tag v-else-if="scope.row.buildstate===1" type="warning">构建中</el-tag>
          <el-tag v-else-if="scope.row.buildstate===2" type="info">已取消</el-tag>
          <el-tag v-else-if="scope.row.buildstate===3" type="success">构建成功</el-tag>
          <el-tag v-else-if="scope.row.buildstate===-1" type="danger">构建失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="所属的项目id" align="center" prop="applicationId"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button
              size="mini"
              type="text"
              v-if="scope.row.buildstate===1"
              icon="el-icon-loading"
              @click="handleBuildAndSeeLog(scope.row,'seeLog')">查看日志
          </el-button>

          <el-button
              size="mini"
              type="text"
              v-if="scope.row.buildstate!==1"
              icon="el-icon-cpu"
              @click="handleBuildAndSeeLog(scope.row,'build')">编译
          </el-button>


          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-if="scope.row.buildstate!==1"
              v-hasPermi="['resource:project:edit']"
          >修改
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['resource:project:remove']"
          >

          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改git项目管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body
               :before-close="closeDialog" :close-on-click-modal="false">
      <editInfo ref="gitInfoRef" :form-data="formData"
                @handelSaveOk="handelSaveOk"/>
    </el-dialog>
    <el-dialog :title="buildTitle" :visible.sync="showBuild" append-to-body :close-on-click-modal="false"
               :before-close="closeBuildDialog">
      <div
          id="terminal"
          ref="terminal"
          class="terminal"/>
    </el-dialog>
  </div>
</template>

<script>
import {listProject, getProject, delProject, buildProject, closebuild} from "@/api/resource/project";

import 'xterm/css/xterm.css'
import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
import {Terminal} from 'xterm'
import 'xterm/css/xterm.css'
import {baseUrl} from "@/utils/ruoyi";


import editInfo from "@/views/resource/project/editInfo";
import {getAppList} from "@/api/resource/application";
import Swal from "sweetalert2";


export default {
  name: "Project",
  components: {
    editInfo
  },
  data() {
    return {
      isBuilding: false,
      terminal: null,
      projectId: null,
      controller: {
        ellipsis: 100,
        modalStyle: {
          height: '600px',
          padding: '5px'
        }
      },

      buildTitle: '编译日志',
      buildState: [
        {
          buildKey: 0,
          value: '未构建'
        },
        {
          buildKey: 1,
          value: '构建中'
        },
        {
          buildKey: 2,
          value: '已取消'
        },
        {
          buildKey: 3,
          value: '构建成功'
        },
        {
          buildKey: -1,
          value: '构建失败'
        },
      ],
      showBuild: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // git项目管理表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        buildstate: null
      },
      formData: {
        applicationId: '',
        id: '',
        name: '',
        url: '',
        branches: '',
        username: '',
        password: '',
        description: '',
        remark: '',
        applicationList: []
      }
    };
  },
  created() {
    this.getList(false);
  },

  mounted() {
    const timer = window.setInterval(() => this.getList(true), 2000)
    this.$once('hook:beforeDestroy', () => {
      clearInterval(timer)
    })

  },

  methods: {
    /** 查询git项目管理列表 */
    getList(isTimer) {
      if (!isTimer) {
        this.loading = true;
      }
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    initform(data) {
      if (data != null) {
        this.formData.applicationId = data.applicationId;
        this.formData.id = data.id;
        this.formData.name = data.name;
        this.formData.url = data.url;
        this.formData.branches = data.branches;
        this.formData.username = data.username;
        this.formData.password = data.password;
        this.formData.description = data.description;
        this.formData.remark = data.remark;
      } else {
        this.formData.applicationId = '';
        this.formData.id = '';
        this.formData.name = '';
        this.formData.url = '';
        this.formData.branches = '';
        this.formData.username = '';
        this.formData.password = '';
        this.formData.description = '';
        this.formData.remark = '';
      }
    },
    handelSaveOk(v) {
      this.open = v;
      this.getList(false);
    },
    closeDialog() {
      if (this.$refs.gitInfoRef !== undefined) {
        this.$refs.gitInfoRef.resetForm();
      }
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList(false);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    openEdit(type, row) {
      getAppList().then(res => {
        if (res.rows.length <= 0) {
          this.$message.warning('没有可用的项目，请先创建项目');
          return
        }
        this.formData.applicationList = res.rows;
        if (type === 'add') {
          this.initform(null);
          this.open = true;
          this.title = "添加git项目管理";
        } else {
          const id = row.id || this.ids
          getProject(id).then(response => {
            if (response.data.buildstate === 1) {
              this.$message.warning('项目正在编译，不允许修改！')
              return
            }
            this.initform(response.data);
            this.open = true;
            this.title = "修改git项目管理";
          });
        }
      }).catch(err => {
        this.$message.error(err);
      })
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.openEdit('add', null)
    },

    closeBuildDialog() {
      this.handleClose();
    },

    handleBuildAndSeeLog(row, type) {
      if (type === 'seeLog') {
        this.showBuild = true;
        this.buildTitle='项目:['+row.name+'] 编译日志'
        this.handleSeeLog(row)
      } else {
        Swal.fire({
          icon: 'success',
          title: 'The current project is building',
          showConfirmButton: false,
          timer: 2000
        }).then((r) => {
          buildProject(row.id)
        })
      }
    },
    handleClose() {
      closebuild(this.projectId).then(res => {
        this.stompClient.disconnect()
        this.terminal.clear()
        this.terminal.clearSelection()
        this.showBuild = false;
        this.buildTitle=''
      })
    },

    /**
     *
     * @param 查看编译日志
     */
    handleSeeLog(project) {
      this.$nextTick(function () {
        this.handleOpenWS(project)
      })
    },

    /**
     * 初始化终端
     */
    initalTerminal() {
      if (this.terminal === null) {
        const rows = parseInt(this.controller.modalStyle.height.replace('px', '')) / 16
        const cols = (document.querySelector('.terminal').offsetWidth - 10) / 8
        this.terminal = new Terminal({
          cursorBlink: true,
          rendererType: 'canvas',
          termName: 'xterm',
          useStyle: true,
          screenKeys: true,
          convertEol: true,
          scrollback: 1000,
          tabstopwidth: 4,
          disableStdin: true,
          rows: parseInt(rows), // 行数
          cols: parseInt(cols),
          fontSize: 14,
          cursorStyle: 'underline', // 光标样式
          theme: {
            foreground: '#AAAAAA', // 字体
            background: '#131D32', // 背景色
            lineHeight: 16
          }
        })
        const container = document.getElementById('terminal')
        this.terminal.open(container, true)
      }

    },

    //开启websokect
    handleOpenWS(project) {
      this.projectId = project.id
      this.initalTerminal();
      const url = baseUrl().concat('/websocket')
      const socket = new SockJS(url, null, {timeout: 15000})
     //let buildheader= '/resp/build/'+project.id+'/'+project.sessionId;

      this.stompClient = Stomp.over(socket)
      this.stompClient.connect({}, (success) => {
        this.stompClient.subscribe('/resp/build/', (msg) => this.terminal.writeln(msg.body))
        this.stompClient.send('/req/build/' + this.projectId)
      })
    },


    /** 修改按钮操作 */
    handleUpdate(row) {
      this.openEdit('update', row)
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除git项目管理编号为"' + ids + '"的数据项？').then(function () {
        return delProject(ids);
      }).then(() => {
        this.getList(false);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('resource/project/export', {
        ...this.queryParams
      }, `project_${new Date().getTime()}.xlsx`)
    },
  },


};
</script>
